package com.yds.bluetooth

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.yds.bluetooth.databinding.ActivityBluetoothBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import android.Manifest

class BluetoothActivity : AppCompatActivity() {
    private lateinit var mBinding: ActivityBluetoothBinding

    companion object {
        private const val TAG = "YDSimon"
        private val PERMISSIONS_REQUIRED = arrayOf(
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )

        private const val PERMISSIONS_REQUEST_CODE = 10
    }

    private val mListBluetoothDevices = mutableListOf<BluetoothDevice>()

    @SuppressLint("MissingPermission")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_bluetooth)
        mBinding.lifecycleOwner = this

        if (!hasPermissions(this)) {
            requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE)
        } else {
            initBluetooth()
        }

        mBinding.mBtnStartScan.setOnClickListener {
            BluetoothHelper.startBleScan {
                mListBluetoothDevices.clear()
                it.forEach { device ->
                    mListBluetoothDevices.add(device)
                    Log.d(TAG, "发现BLE设备: ${it.size} 名称 - ${device.name}, 地址 - ${device.address}")
                }
            }
        }

        mBinding.mBtnStopScan.setOnClickListener {
            BluetoothHelper.stopBleScan()
        }

        mBinding.mBtnConnect.setOnClickListener {
            if (mListBluetoothDevices.isNotEmpty()) {
                BluetoothHelper.connectBleDevice(this@BluetoothActivity, mListBluetoothDevices[0])
            }
        }

        mBinding.mBtnDisconnect.setOnClickListener {
            BluetoothHelper.disconnectBleDevice()
        }

        mBinding.mBtnBoard.setOnClickListener {
            BluetoothHelper.writeBleData("AA 01 40 0C 00 BF 5F 02 46 31 34 41 32 33 34 35 36 38 39")
        }

        mBinding.mBtnCreate.setOnClickListener {
            BluetoothHelper.writeBleData("AA01100D0004101E01000000000002000201062E")
        }

        mBinding.mBtnCurrent.setOnClickListener {
            BluetoothHelper.writeBleData("AA01100C0054F41E0207000000000100002A2E")
        }
    }

    private fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all {
        ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            if (PackageManager.PERMISSION_GRANTED == grantResults.firstOrNull()) {
                initBluetooth()
            } else {
                Toast.makeText(this, "Permission request denied", Toast.LENGTH_LONG).show()
                if (!hasPermissions(this)) {
                    requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE)
                }
            }
        }
    }

    @SuppressLint("MissingPermission")

    /*** 作者: YDS 时间: 2024/7/4 15:49 描述: 连接设备 ***/
    private fun initBluetooth() {
        BluetoothHelper.init(this)
    }
    @SuppressLint("MissingPermission")
    private fun connectDevice() {
        if (mListBluetoothDevices.isNotEmpty()) {
            lifecycleScope.launch(Dispatchers.Main) {

            }
        }
    }

}